package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constat.MessageConstant;
import com.itheima.constat.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * @authou: fu
 * @date:Created in 2019/12/5
 * @description:
 * @version:1.0
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    private SetmealService setmealService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/getSetmeal")
    public Result getSetmeal(){
        Jedis jedis = jedisPool.getResource();

        try {
            String jsontomax = jedis.get(RedisConstant.SETMEAL_REDIS_RESOURCES);
            if (jsontomax == null || jsontomax.length()==0){
                List<Setmeal> list = setmealService.findAll();
                String jsonList = JSON.toJSONString(list);
                jedis.set(RedisConstant.SETMEAL_REDIS_RESOURCES, jsonList);
                return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, list);
            }else {
                List<Setmeal> list = JSON.parseArray(jsontomax, Setmeal.class);
                return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        } finally {
            jedis.close();
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Setmeal setmeal = setmealService.findById(id);
            return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }

}
